package com.le.buddha.service;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.le.buddha.mobile.enums.SysConfigEnum;
import io.reactivex.Flowable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ALiGptServiceImpl implements ALiGptService {
    @Resource
    private ISysConfigService sysConfigService;

    @Override
    public Flowable<ApplicationResult> send(String message, String sessionId) throws Exception {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey("sk-0d7dcec51e6b4249b4924eba4f0a16af")
                // 替换为实际的应用 ID
                .appId(sysConfigService.queryValueByCode(SysConfigEnum.智能体APPID.getCode()))
                .prompt(message)
                // 增量输出
                .incrementalOutput(true)
                .sessionId(sessionId)
                .build();
        Application application = new Application();
        // .streamCall（）：流式输出内容
        Flowable<ApplicationResult> result = application.streamCall(param);
        return result;
//        result.blockingForEach(data -> {
////            System.out.printf("%s\n",
////                    data.getOutput().getText());
//            System.out.println(data.getOutput().getText());
//        });
    }
//    public static void main(String[] args) {
//        try {
//            streamCall();
//        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
//            System.out.printf("Exception: %s", e.getMessage());
//            System.out.println("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
//        }
//        System.exit(0);
//    }

}
